package cn.sun.pet.service.impl;

import cn.sun.basic.service.impl.BaseServiceImpl;
import cn.sun.pet.domain.Pet;
import cn.sun.pet.domain.PetDetail;
import cn.sun.pet.mapper.PetDetailMapper;
import cn.sun.pet.mapper.PetMapper;
import cn.sun.pet.query.PetQuery;
import cn.sun.pet.service.IPetService;
import cn.sun.user.domain.User;
import cn.sun.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet, PetQuery> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void delete(Long id) {
        //除了删除自己还要删除详情
        petMapper.delete(id);
        //通过PetId删除PetDetail
        petDetailMapper.removeByPetId(id);
    }

    @Override
    public void save(Pet pet) {
        petMapper.save(pet);
        PetDetail detail = pet.getDetail();
        if (detail!=null){
            detail.setPet_id(pet.getId());
            petDetailMapper.save(detail);
        }
    }

    @Override
    public void update(Pet pet) {
        petMapper.update(pet);
        //是否有详情
        PetDetail detail = pet.getDetail();
        if (detail!=null){
            if (detail.getId()!=null){
                //有详情
                petDetailMapper.update(detail);
            }else{
                petDetailMapper.save(detail);
            }
        }
    }

    @Override
    public PetDetail getDetailByPetId(Long petId) {
        return petDetailMapper.loadByPetId(petId);
    }

    //flag标识 1上架 0下架
    @Override
    public void onsaleOrOffsale(List<Long> ids, int flag) {

        if (flag==1){
            //上架：上架服务们ids（批量修改），上架时间
            Map<String,Object> params = new HashMap<>();
            params.put("ids",ids);
            params.put("onsaletime",new Date());
            petMapper.onsale(params);
        }else{
            //下架
            Map<String,Object> params = new HashMap<>();
            params.put("ids",ids);
            params.put("offsaletime",new Date());
            petMapper.offSale(params);
        }
    }

    @Autowired
    private UserMapper userMapper;
    @Override
    public void adopt(Long id, Long loginInfoId) {
        Pet pet = petMapper.findById(id);
        // 一 修改信息
        //1 宠物下架
        pet.setState(0);
        pet.setOffsaletime(new Date());
        //2 绑定用户
        User user = userMapper.findByLoginInfoId(loginInfoId);
        pet.setUser_id(user.getId());
        pet.setUser(user);
        petMapper.update(pet);

        //@TODO 二 创建订单
    }

    @Override
    public Pet getPetDetailByPetId(Long petId) {
        return petMapper.loadByIdDetail(petId);
    }
}
